#include "LoopThreadPool.h"
#include "EventLoop.h"
#include "EventLoopThread.h"

#include "Logger.h"

LoopThreadPool::LoopThreadPool(EventLoop* main_thread) : base_loop_(main_thread), thread_num_(0), next_(0) {}

void LoopThreadPool::SetThreadNum(const int num) {
    thread_num_ = num;
    LOG_INFO("thread nums:%d", num);
}

void LoopThreadPool::start() {
    threads_.resize(thread_num_);
    loops_.resize(thread_num_);
    for (int i = 0; i < thread_num_; i++) {
        EventLoopThread* thread = new EventLoopThread();
        // Use unique_ptr automatically delete LoopThread
        threads_[i] = std::unique_ptr<EventLoopThread>(thread);
        loops_[i] = thread->SelfEventLoop();
    }
}

EventLoop* LoopThreadPool::GetNextLoop() {
    if (thread_num_ == 0) {
        // 分配给主线程
        return base_loop_;
    } else {
        // 轮询分配
        next_ = (next_ + 1) % thread_num_;
        LOG_INFO("despatched ioloop id is %d", next_);
        return loops_[next_];
    }
}
